package com.ytzq.itom.action;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ytzq.base.constants.ERROR_CODE;
import com.ytzq.base.constants.LOG_TYPE;
import com.ytzq.base.dict.Dict;
import com.ytzq.base.function.RequestParameter;
import com.ytzq.base.function.ResponseParameter;
import com.ytzq.base.helper.PageHelper;
import com.ytzq.base.helper.StringHelper;
import com.ytzq.base.log.Logger;
import com.ytzq.itom.function.ForwardFunction;
import com.ytzq.web.action.ActionResult;
import com.ytzq.web.action.BaseAction;


/**
 * Function功能号的服务入口
 * @author 门士松  20121031
 * @version 1.0
 * @since
 */
public class FunctionServiceAction extends BaseAction {
	private Logger logger = Logger.getLogger(this.getClass());
	private ResponseParameter responseParameter = new ResponseParameter();
	public ActionResult doDefault() {
		if (this.isPostBack()) {
			String jsonContent = "";
			try {
				//标准HTTP请求
				jsonContent = getRequest().getParameter("jsonContent");
				//非标准HTTP（android，IOS）请求时处理post的内容体作为一个参数
				if(StringHelper.isEmpty(jsonContent)) { //
					try {
						InputStreamReader isr = new InputStreamReader(this.getRequest().getInputStream(),"UTF-8");	
						StringBuffer sb = new StringBuffer();
						while (isr.ready()) {
	                          sb.append((char) isr.read());
	                    }
						jsonContent = sb.toString();
					} catch (IOException e1) {
						logger.error(LOG_TYPE.SYSTEM, e1);
						responseParameter.setErrorCodeAndInfo(ERROR_CODE._5);
					}
				}else{
					logger.info(LOG_TYPE.BUSINESS,"httpRequest请求的json参数为："+jsonContent);
					ForwardFunction function = new ForwardFunction();
					String clientIP = this.getIpAddress();
					String path = this.getRequest().getContextPath();
					String basePath = this.getRequest().getScheme()+"://"+getRequest().getServerName()+":"+getRequest().getServerPort()+path;
					Gson gson = new GsonBuilder().serializeNulls().create();
					@SuppressWarnings("unchecked")
					Map<String, Map<String,String>> params = (Map<String,Map<String,String> >) gson.fromJson(jsonContent, new TypeToken<Map<String, Map<String,String>>>() {}.getType());    
					Map<String,String> head = params.get("head");
					Map<String,String> content = params.get("content");
					RequestParameter requestParameter = new RequestParameter();
					requestParameter.setClientIP(clientIP);
					requestParameter.setBasePath(basePath);
					requestParameter.setSessionID(head.get("session_id"));
					requestParameter.setFuncNo(head.get("func_on"));
					requestParameter.setUserID(head.get("user_id"));
					requestParameter.setParams(content);
					responseParameter = function.execute(requestParameter);
				}
			} catch (Exception e) {
				logger.error(LOG_TYPE.SYSTEM, e);
				responseParameter.setErrorCodeAndInfo(ERROR_CODE._6);
			}	
		} else { //get请求
			logger.error(LOG_TYPE.SYSTEM, Dict.getErrorInfo(ERROR_CODE._7),Dict.getErrorInfo(ERROR_CODE._7));
			responseParameter.setErrorCodeAndInfo(ERROR_CODE._7);
		}
		sendHttpResponse(responseParameter);
		return null;
	}
	/**
	 * 返回处理
	 * @param response
	 * @param request
	 * @param response2
	 */
	private void sendHttpResponse(ResponseParameter responseParameter) {
		logger.info(LOG_TYPE.BUSINESS,"httpRequest请求处理后返回的信息为："+responseParameter);
		try {
        	String str= toJson(responseParameter);
            this.getResponse().getWriter().print(str);
            this.getResponse().getWriter().flush();
            this.getResponse().getWriter().close();
		} catch (IOException e) {
			logger.error(LOG_TYPE.SYSTEM, e);
		}
	}
	/**
	 * 将responseParameter 转为JSON格式
	 * @param responseParameter
	 * @return
	 */
    private String toJson(ResponseParameter responseParameter){
		Gson gson = new GsonBuilder().serializeNulls().create();
		//如果分页信息为空，则生成JSON的时过滤掉page（分页）对象
    	if(responseParameter.getPage()==null){
    		gson = new GsonBuilder()
    			.serializeNulls()
    			.addSerializationExclusionStrategy(new PageHelperExclusionStrategy()) //设置过滤
    			.create();
    	}
		return gson.toJson(responseParameter);
    }
	/**
	 * 自定义的一个GSON 序列化对象过滤器：过滤掉PageHelper(分页)对象
	 */
	private class PageHelperExclusionStrategy implements ExclusionStrategy {
		private Class<?> clazz = PageHelper.class;
		@Override
		public boolean shouldSkipClass(Class<?> arg0) {
			return false;
		}
		@Override
		public boolean shouldSkipField(FieldAttributes f) {
			return clazz.equals(f.getDeclaredClass());
		}
	}
}
